package com.sskj.level.ui.fragment;


import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;

import com.afollestad.materialdialogs.MaterialDialog;
import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.sskj.common.adapter.slimadapter.IViewInjector;
import com.sskj.common.adapter.slimadapter.SlimAdapter;
import com.sskj.common.adapter.slimadapter.SlimInjector;
import com.sskj.common.base.App;
import com.sskj.common.rxbus2.RxBus;
import com.sskj.common.rxbus2.Subscribe;
import com.sskj.common.rxbus2.ThreadMode;
import com.sskj.common.util.DisposUtil;
import com.sskj.common.util.ToastUtil;
import com.sskj.level.R;
import com.sskj.level.R2;
import com.sskj.level.bean.BuySellEnum;
import com.sskj.level.bean.CoinType;
import com.sskj.level.bean.TradeListBean;
import com.sskj.level.bean.WinLossBean;
import com.sskj.level.component.DaggerUserDataComponent;
import com.sskj.level.presenter.CurrentHolderFragmentPresenter;
import com.sskj.level.util.TipLevelUtil;
import com.sskj.lib.RConfig;
import com.sskj.lib.RxBusCode;
import com.sskj.lib.base.BaseFragment;
import com.sskj.lib.bean.CoinBean;
import com.sskj.lib.bean.MainTabChange;
import com.sskj.lib.bean.StockCoinBean;
import com.sskj.lib.bean.UserData;
import com.sskj.lib.model.room.UserViewModel;
import com.sskj.lib.util.TipUtil;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import javax.inject.Inject;

import butterknife.BindView;
import io.reactivex.Flowable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;

@Route(path = RConfig.LEVEL_FRAGMENT_CURRENT_HOLDER)//当前委托
public class CurrentHolderFragment extends BaseFragment<CurrentHolderFragmentPresenter> {
    @BindView(R2.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R2.id.includeEmpty)
    View includeEmpty;

    private SlimAdapter<TradeListBean> slimAdapter;
    @Autowired
    String code;
    private int curPos;
    @Inject
    UserViewModel userViewModel;

    private Disposable subscribe;
    private MaterialDialog setTip;
    private UserData userData;
    private MaterialDialog cancelTip;


    @Override
    protected int getLayoutId() {
        return R.layout.level_fragment_current_holder;
    }

    @Override
    public CurrentHolderFragmentPresenter getPresenter() {
        return new CurrentHolderFragmentPresenter();
    }

    @Override
    public void initView() {
        RxBus.getDefault().register(this);
        DaggerUserDataComponent.create().inject(this);

        ARouter.getInstance().inject(this);

        recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        slimAdapter = SlimAdapter.create().register(R.layout.level_recy_item_entrust, new SlimInjector<TradeListBean>() {
            @Override
            public void onInject(TradeListBean data, IViewInjector injector, List payloads) {
                injector
                        .textColor(R.id.tv_mm, ContextCompat.getColor(App.INSTANCE, data.getOtype().equals(BuySellEnum.BUY.getType()) ? BuySellEnum.BUY.getColorRes() : BuySellEnum.SELL.getColorRes()))
                        .text(R.id.tv_mm, data.getOtype().equals(BuySellEnum.BUY.getType()) ? BuySellEnum.BUY.getTitle() : BuySellEnum.SELL.getTitle())//买入卖出
                        .text(R.id.tv_bz, data.getPname())//币种类型
                        .text(R.id.tv_time, data.getAddtime())//时间
                        .text(R.id.tv_first_left, data.getMarketLimit())//类型
                        .text(R.id.level_fd_type, App.INSTANCE.getString(R.string.levelJavaCurrentHolderFragment1) + data.getFdyk())//盈亏
                        .text(R.id.tv_first_right, data.getBuynum())//委托量
                        .text(R.id.tv_second_left, data.getBuyprice())//委托价
                        .text(R.id.tv_second_right, data.getTotalprice())//保证金
                        .text(R.id.tv_third_left, data.getStopwin())//止盈价
                        .text(R.id.tv_third_right, data.getSxfee())//手续费
                        .text(R.id.tv_four_left, data.getStoploss())//止损价
//                        .background(R.id.level_fd_type, ContextCompat.getDrawable(App.INSTANCE, Double.valueOf(data.getFdyk()) > 0 ? R.drawable.level_shape_green2 : R.drawable.level_shape_red2))

                        .clicked(R.id.tvCancel, v -> {
                            curPos = slimAdapter.getData().indexOf(data);
                            cancel();
                        });
            }
        }).attachTo(recyclerView).updateData(new ArrayList());
        userViewModel.getUsers().observe(this, users -> {
            if (users != null && users.size() > 0) {
                userData = users.get(0);
            } else {
                userData = null;
            }
            refresh();
        });
        startTimer();
    }

    /**
     * 撤销订单
     */
    private void cancel() {
        TradeListBean dataItem = slimAdapter.getDataItem(curPos);
        cancelTip = TipLevelUtil.showTradeCancel(getActivity(), dataItem.getOtype(), dataItem.getBuynum(), dataItem.getBuyprice(), () -> {
            cancelTip.dismiss();
            mPresenter.cancelOrder(slimAdapter.getDataItem(curPos).getEn_id() + "");

        });
        cancelTip
                .show();
    }

    public void pingCangSuccess() {
        userViewModel.update();
        refresh();
    }

    public void cancelOrderSuccess() {
        userViewModel.update();
        refresh();
    }

    /**
     * 刷新
     */
    @Subscribe(code = RxBusCode.LEVEL_FRESH, threadMode = ThreadMode.MAIN)
    public void refresh() {
        if (mPresenter != null && userData != null) {
            mPresenter.getTradeList(code);
        } else {
            DisposUtil.close(subscribe);
            showEmpty();
        }
    }

    /**
     * 显示无数据布局
     */
    public void showEmpty() {
        AndroidSchedulers.mainThread().scheduleDirect(() -> {

            if (includeEmpty != null) {
                includeEmpty.setVisibility(View.VISIBLE);
                recyclerView.setVisibility(View.GONE);
            }
            if (slimAdapter != null) {
                slimAdapter.updateData(new ArrayList<>());
            }
        });

    }

    /**
     * 平仓
     */
    private void pingCang() {
        TradeListBean dataItem = slimAdapter.getDataItem(curPos);
        boolean isBuy = dataItem.getOtype().equals(BuySellEnum.BUY.getType());
        TipLevelUtil.getPingcangTip(getActivity(), isBuy, dataItem.getNewprice(), dataItem.getBuynum(), (num) -> {
            mPresenter.pingCang(num, slimAdapter.getDataItem(curPos).getHold_id() + "");

        }).show();
    }

    /**
     * 设置点位
     */
    public void setStop(WinLossBean winLossBean) {
        TradeListBean dataItem = slimAdapter.getDataItem(curPos);
        setTip = TipLevelUtil.showTradeSet(getActivity(),
                dataItem.getOtype(),
                dataItem.getNewprice(),
                winLossBean.getMin_zy(),
                winLossBean.getMax_zy(),
                winLossBean.getMin_zs(),
                winLossBean.getMax_zs(),
                list -> {
                    mPresenter.setStop(dataItem.getHold_id() + "",
                            TextUtils.isEmpty(list.get(0)) ? "0" : list.get(0),
                            TextUtils.isEmpty(list.get(1)) ? "0" : list.get(1));
                }
        );
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void updatePrice(CoinBean stockCoinBean) {
        if (setTip != null && setTip.isShowing()) {
            if (stockCoinBean.getCode().equals(slimAdapter.getDataItem(curPos).getPname())) {
                TipLevelUtil.changeTradeSet(setTip, stockCoinBean.getPrice());
            }
        }

    }

    private void startTimer() {
        if (userData == null)
            return;
        DisposUtil.close(subscribe);
        subscribe = Flowable.interval(0, 5, TimeUnit.SECONDS)
                .onBackpressureDrop()
                .subscribe(i -> mPresenter.getTradeList(code));
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void changeTab(MainTabChange mainTabChange) {
        if (mainTabChange.getPos() == 2) {
            if (mPresenter != null && userData != null) {
                startTimer();
            }
        } else {
            DisposUtil.close(subscribe);
        }
    }

    @Override
    public void onDestroy() {
        DisposUtil.close(subscribe);
        super.onDestroy();
    }

    /**
     * 刷新币种
     *
     * @param coinType
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void refresh(CoinType coinType) {
        code = coinType.getCode();
        if (userData == null)
            return;
        mPresenter.getTradeList(code);
    }


    public void updateUI(List<TradeListBean> data) {
        if (data.size() == 0) {
            if (recyclerView == null)
                return;
            recyclerView.setVisibility(View.GONE);
            includeEmpty.setVisibility(View.VISIBLE);
        } else {
            if (recyclerView == null)
                return;
            recyclerView.setVisibility(View.VISIBLE);
            includeEmpty.setVisibility(View.GONE);
            slimAdapter.updateData(data);
        }
    }
}
